<template>
  <CommonPage>
    <template #action>
      <NButton mr-5 type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增用户
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="用户名" :label-width="50">
        <n-input
          v-model:value="queryItems.username"
          type="text"
          placeholder="请输入用户名"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="昵称" :label-width="50">
        <n-input
          v-model:value="queryItems.nickname"
          type="text"
          placeholder="请输入用户名"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="状态" :label-width="50">
        <n-select v-model:value="queryItems.status" clearable :options="DATA_STATUS" />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="520px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="登录帐号"
          path="username"
          :rule="{
            required: true,
            message: '请输入登录帐号',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.username" placeholder="请输入登录帐号" />
        </n-form-item>
        <n-form-item
          label="用户昵称"
          path="nickname"
          :rule="{
            required: true,
            message: '请输入用户昵称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.nickname" placeholder="请输入用户昵称" />
        </n-form-item>
        <n-form-item
          label="用户密码"
          path="password"
          :rule="{
            required: modalAction !== 'edit',
            message: '请输入密码',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.password" placeholder="请输入用户密码" />
        </n-form-item>

        <n-form-item
          label="角色"
          path="role_ids"
          :rule="{
            required: true,
            type: 'array',
            message: '请选择角色',
            trigger: ['input', 'blur'],
          }"
        >
          <n-select
            v-model:value="modalForm.role_ids"
            :options="roles"
            label-field="name"
            value-field="id"
            clearable
            filterable
            multiple
          />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="modalForm.status" size="small" name="status">
            <n-radio-button
              v-for="item in DATA_STATUS"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </n-radio-group>
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { CommonPage, MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { NButton, NSwitch, NTag } from 'naive-ui'
import { useTemplateRef } from 'vue'
import api from './api'

defineOptions({ name: 'ManagerList' })

const $table = useTemplateRef('$table')
const queryItems = ref({})

// 状态字典-> 数据状态
const { DATA_STATUS } = $dict('DATA_STATUS')

onMounted(() => {
  $table.value?.handleSearch()
})

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '用户',
  initForm: { status: '0' },
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '用户名', key: 'username', width: 150 },
  { title: '昵称', key: 'nickname', width: 150 },
  {
    title: '角色',
    key: 'roles',
    width: 200,
    render: (row) => {
      if (row.roles?.length) {
        return row.roles.map((item, index) =>
          h(
            NTag,
            { size: 'small', type: 'success', style: index > 0 ? 'margin-left: 8px;' : '' },
            { default: () => item.name },
          ),
        )
      }
      else if (row.is_super === '1') {
        return h(NTag, { size: 'small', type: 'success' }, { default: () => '昊天金阙至尊' })
      }
      return '暂无角色'
    },
  },
  {
    title: '状态',
    key: 'status',
    render: row =>
      h(
        NSwitch,
        {
          value: row.status,
          loading: !!row.statusLoading,
          checkedValue: '0',
          unCheckedValue: '1',
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '停用',
        },
      ),
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        row.is_super !== '1'
        && h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => handleManagerEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:tool text-14' }),
          },
        ),

        row.is_super !== '1'
        && h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => handleReset(row),
          },
          {
            default: () => '重置密码',
            icon: () => h('i', { class: 'i-radix-icons:reset text-14' }),
          },
        ),
        row.is_super !== '1'
        && h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id, row.nickname),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

// 重置密码
function handleReset(row) {
  if (!row.id && row.id !== 0)
    return
  const d = $dialog.warning({
    content: `确定要重置《${row.nickname}》的密码为123456吗？`,
    title: '提示',
    positiveText: '确定',
    negativeText: '取消',
    async onPositiveClick() {
      try {
        d.loading = true
        const { message } = await api.resetPassword({ id: row.id })
        $message.success(message)
      }
      finally {
        d.loading = false
      }
    },
  })
}

function handleManagerEdit(row) {
  const role_ids = row.roles.map(item => item.id)
  handleOpen({
    action: 'edit',
    title: '编辑用户',
    row: {
      id: row.id,
      username: row.username,
      role_ids,
      nickname: row.nickname,
      status: row.status,
    },
    onOk: onSave,
  })
}

function onSave() {
  handleSave({
    api: () => api.update(modalForm.value),
    cb: () => $message.success('编辑成功'),
  })
}

async function handleEnable(row) {
  row.statusLoading = true
  try {
    const { message } = await api.updateStatus({ id: row.id, status: row.status === '0' ? '1' : '0' })
    row.status = row.status === '0' ? '1' : '0'
    $message.success(message)
  }
  finally {
    row.statusLoading = false
  }
}

const roles = ref([])
api.getAllRoles().then(({ data = [] }) => (roles.value = data))
</script>
